package com.luo.backend.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luo.backend.dto.FoodResponse;
import com.luo.backend.dto.MerchantFoodRequest;
import com.luo.backend.entity.Food;
import com.luo.backend.repository.FoodRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家菜品管理服务
 */
@Service
public class MerchantFoodService {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantFoodService.class);
    
    @Autowired
    private FoodRepository foodRepository;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 获取商家菜品列表
     */
    public List<FoodResponse> getFoods(Long merchantId, Integer status) {
        logger.info("获取商家菜品列表 - merchantId: {}, status: {}", merchantId, status);
        
        List<Food> foods;
        
        if (status != null) {
            // 按状态筛选
            foods = foodRepository.findByMerchantIdAndStatus(merchantId, status);
        } else {
            // 获取所有菜品（包括上架和下架的）
            foods = foodRepository.findAllByMerchantIdOrderByCreatedAtDesc(merchantId);
        }
        
        return foods.stream()
            .map(FoodResponse::new)
            .collect(Collectors.toList());
    }
    
    /**
     * 获取菜品详情
     */
    public FoodResponse getFoodDetail(Long merchantId, Long foodId) {
        logger.info("获取菜品详情 - merchantId: {}, foodId: {}", merchantId, foodId);
        
        Food food = foodRepository.findById(foodId)
            .orElseThrow(() -> new RuntimeException("菜品不存在"));
        
        // 验证菜品属于该商家
        if (!food.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权访问该菜品");
        }
        
        return new FoodResponse(food);
    }
    
    /**
     * 新增菜品
     */
    @Transactional
    public FoodResponse createFood(Long merchantId, MerchantFoodRequest request) {
        logger.info("新增菜品 - merchantId: {}, name: {}", merchantId, request.getName());
        
        // 验证必填字段
        if (request.getName() == null || request.getName().trim().isEmpty()) {
            throw new RuntimeException("菜品名称不能为空");
        }
        if (request.getPrice() == null) {
            throw new RuntimeException("价格不能为空");
        }
        
        Food food = new Food();
        food.setMerchantId(merchantId);
        food.setCategoryId(request.getCategoryId());
        food.setName(request.getName());
        food.setDescription(request.getDescription());
        food.setImage(request.getImage());
        food.setPrice(request.getPrice());
        food.setOriginalPrice(request.getOriginalPrice());
        food.setStock(request.getStock() != null ? request.getStock() : 0);
        food.setSoldCount(0);
        food.setRating(new BigDecimal("5.00")); // 默认评分
        food.setRatingCount(0);
        food.setIsHot(request.getIsHot() != null ? request.getIsHot() : 0);
        food.setIsRecommended(request.getIsRecommended() != null ? request.getIsRecommended() : 0);
        food.setStatus(request.getStatus() != null ? request.getStatus() : 1);
        
        // 转换List为JSON字符串
        food.setTags(convertListToJson(request.getTags()));
        food.setSpiceLevels(convertListToJson(request.getSpiceLevels()));
        
        Food savedFood = foodRepository.save(food);
        
        logger.info("新增菜品成功 - foodId: {}", savedFood.getId());
        return new FoodResponse(savedFood);
    }
    
    /**
     * 修改菜品
     */
    @Transactional
    public FoodResponse updateFood(Long merchantId, Long foodId, MerchantFoodRequest request) {
        logger.info("修改菜品 - merchantId: {}, foodId: {}", merchantId, foodId);
        
        Food food = foodRepository.findById(foodId)
            .orElseThrow(() -> new RuntimeException("菜品不存在"));
        
        // 验证菜品属于该商家
        if (!food.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权修改该菜品");
        }
        
        // 更新字段
        if (request.getCategoryId() != null) {
            food.setCategoryId(request.getCategoryId());
        }
        if (request.getName() != null && !request.getName().trim().isEmpty()) {
            food.setName(request.getName());
        }
        if (request.getDescription() != null) {
            food.setDescription(request.getDescription());
        }
        if (request.getImage() != null) {
            food.setImage(request.getImage());
        }
        if (request.getPrice() != null) {
            food.setPrice(request.getPrice());
        }
        if (request.getOriginalPrice() != null) {
            food.setOriginalPrice(request.getOriginalPrice());
        }
        if (request.getStock() != null) {
            food.setStock(request.getStock());
        }
        if (request.getIsHot() != null) {
            food.setIsHot(request.getIsHot());
        }
        if (request.getIsRecommended() != null) {
            food.setIsRecommended(request.getIsRecommended());
        }
        if (request.getStatus() != null) {
            food.setStatus(request.getStatus());
        }
        if (request.getTags() != null) {
            food.setTags(convertListToJson(request.getTags()));
        }
        if (request.getSpiceLevels() != null) {
            food.setSpiceLevels(convertListToJson(request.getSpiceLevels()));
        }
        
        food.setUpdatedAt(LocalDateTime.now());
        Food savedFood = foodRepository.save(food);
        
        logger.info("修改菜品成功 - foodId: {}", foodId);
        return new FoodResponse(savedFood);
    }
    
    /**
     * 删除菜品
     */
    @Transactional
    public void deleteFood(Long merchantId, Long foodId) {
        logger.info("删除菜品 - merchantId: {}, foodId: {}", merchantId, foodId);
        
        Food food = foodRepository.findById(foodId)
            .orElseThrow(() -> new RuntimeException("菜品不存在"));
        
        // 验证菜品属于该商家
        if (!food.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权删除该菜品");
        }
        
        foodRepository.delete(food);
        logger.info("删除菜品成功 - foodId: {}", foodId);
    }
    
    /**
     * 更新菜品状态（上下架）
     */
    @Transactional
    public void updateFoodStatus(Long merchantId, Long foodId, Integer status) {
        logger.info("更新菜品状态 - merchantId: {}, foodId: {}, status: {}", merchantId, foodId, status);
        
        Food food = foodRepository.findById(foodId)
            .orElseThrow(() -> new RuntimeException("菜品不存在"));
        
        // 验证菜品属于该商家
        if (!food.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权修改该菜品状态");
        }
        
        food.setStatus(status);
        food.setUpdatedAt(LocalDateTime.now());
        foodRepository.save(food);
        
        logger.info("更新菜品状态成功 - foodId: {}, status: {}", foodId, status);
    }
    
    /**
     * 将List转换为JSON字符串
     */
    private String convertListToJson(List<String> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            logger.error("转换List为JSON失败", e);
            return null;
        }
    }
}

